﻿<template>
  <div class="reset-password-container">
    <el-form
      :model="form"
      :rules="rules"
      ref="resetForm"
      label-width="120px"
      class="reset-form"
    >
      <el-form-item label="原先密码" prop="currentPassword">
        <el-input
          type="password"
          v-model="form.currentPassword"
          autocomplete="current-password"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="password"
          v-model="form.password"
          autocomplete="new-password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="form.confirmPassword"
          autocomplete="new-password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetPassword">重置密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton } from "element-plus";
import { useRouter } from "vue-router";
import request from "@/utils/request.js";
import { useTokenStore } from "@/stores/token.js";

const router = useRouter();

const tokenStore = useTokenStore();

const uploadHeaders = {
  Authorization: "Bearer " + tokenStore.getToken(),
};

const form = ref({
  currentPassword: "",
  password: "",
  confirmPassword: "",
});

const rules = {
  currentPassword: [
    { required: true, message: "请输入原先密码", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
  ],
};

const resetPassword = async () => {
  try {
    const response = await request.patch(
      "/api/user/updatePsw",
      {
        old_pwd: form._rawValue.currentPassword,
        new_pwd: form._rawValue.password,
        re_pwd: form._rawValue.confirmPassword,
      },
      {
        headers: uploadHeaders,
      }
    );
    ElMessage.success("密码重置成功");
    router.push("/login");
  } catch (error) {
    console.error("Error resetting password:", error);
    ElMessage.error("密码重置失败");
  }
};
</script>

<style scoped>
.reset-password-container {
  max-width: 400px;
  margin: 0 auto;
  margin-top: 50px;
}

.reset-form {
  margin-top: 20px;
}
</style>
